package apps.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import webframe.common.helper.MD5HashHelper;
import apps.web.controller.base.MyBaseCommandController;
import apps.web.model.User;

public class CIQUserEditController extends MyBaseCommandController {

	@Override
	protected ModelAndView handleInner(HttpServletRequest request,
			HttpServletResponse response, Object command) {
		User user = (User) command;
		List<User> list = getServiceContainer().getUserService()
				.findCIQUserByUsername(user.getUsername());
		Map<String, Object> map = new HashMap<String, Object>();
		if (user.getId() == null) {
			// create
			if (list.size() != 0) {
				user.setErrorInfo("添加新纪录失败,此用户名已存在!");
				map.put("user", user);
				return new ModelAndView(getFailureView(), "map", map);
			}
			user.setRegDate(new Date());
			user.setPassword(MD5HashHelper.hash("1234").toLowerCase());
			user = getServiceContainer().getUserService().saveCIQUser(user);
		} else {
			// modify
			if (list.size() == 1 && !list.get(0).getId().equals(user.getId())) {
				user.setErrorInfo("修改记录失败,此用户名和别的记录重复!");
				map.put("user", user);
				return new ModelAndView(getFailureView(), "map", map);
			}
			user.setRegDate(list.get(0).getRegDate());
			user.setPassword(list.get(0).getPassword());
			getServiceContainer().getUserService().updateCIQUser(user);
		}
		return new ModelAndView(new RedirectView("CIQUserSearch.do?id="
				+ user.getId()), "map", map);
	}

}
